package cn.xyy.system.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import cn.xyy.common.domain.mvc.Page;
import cn.xyy.common.domain.system.auth.Job;
import cn.xyy.common.domain.system.auth.JobVO;
import cn.xyy.common.utils.StringUtils;
import cn.xyy.jdbc.BaseDao;

/**
 * 岗位数据持久层
 * 
 * @author xyy
 *
 */
@Repository
public class JobDao extends BaseDao {

	public Page<Job> selectPage(JobVO vo) {
		List<Job> list = super.select(getSqlPageHandle().handlerPagingSQL(pageSql(vo, 0), vo.getPage(), vo.getLimit()),
				null, Job.class);
		int count = super.getJdbcTemplate().queryForObject(pageSql(vo, 1), null, Integer.class);
		Page<Job> page = new Page<Job>(list, count, vo.getLimit(), vo.getPage());
		return page;
	}

	private String pageSql(JobVO vo, int type) {
		StringBuilder sql = new StringBuilder();
		if (type == 0) {
			sql.append("select * from t_sys_job ");
		} else {
			sql.append("select count(*) from t_sys_job ");
		}
		sql.append(" where 1=1");

		if (StringUtils.isNotBlank(vo.getName())) {
			sql.append(" and name like '%").append(vo.getName().trim() + "%' ");
		}

		if (vo.getStatus() != null) {
			sql.append(" and status=" + vo.getStatus() + "");
		}
		if (type == 0) {
			if (StringUtils.isNotBlank(vo.getSidx())) {
				if ((vo.getSord().trim().equalsIgnoreCase("asc"))) {
					sql.append(" order by " + vo.getSidx().split(" ")[0] + " asc");
				} else {
					sql.append(" order by " + vo.getSidx().split(" ")[0] + " desc");
				}
			} else {
				sql.append(" order by sorts asc");
			}
		}
		return sql.toString();
	}

	public List<Job> selectAll() {
		StringBuilder sql = new StringBuilder();
		sql.append("select * from t_sys_job where status=1 order by sorts asc");
		return super.select(sql.toString(), Job.class);
	}

	public int updateState(String id, int state) {
		StringBuilder sql = new StringBuilder();
		sql.append("update t_sys_job set status=? where job_id=?");
		return super.insertOrUpdateOrDelete(sql.toString(), new Object[] { state, id });
	}

}
